package com.xiaoye.digitaltwin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaoye.digitaltwin.common.R;
import com.xiaoye.digitaltwin.entity.Baopocontrol;
import com.xiaoye.digitaltwin.entity.Neiyacontrol;
import com.xiaoye.digitaltwin.entity.Student;
import com.xiaoye.digitaltwin.entity.Waiyacontrol;
import com.xiaoye.digitaltwin.service.IBaopocontrolService;
import com.xiaoye.digitaltwin.service.INeiyacontrolService;
import com.xiaoye.digitaltwin.service.IWaiyacontrolService;
import com.xiaoye.digitaltwin.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 学生相关
 * Create by xiaoye on 2023/3/22
 */

@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    //头像存储路径
    @Value("${digital.path.avatar}")
    private String avatarPath;

    @Autowired
    private IWaiyacontrolService waiyacontrolService;

    @Autowired
    private INeiyacontrolService neiyacontrolService;

    @Autowired
    private IBaopocontrolService baopocontrolService;
    /**
     * 学生的登录
     * @param request
     * @param student
     * @return
     */
    @PostMapping("/login")
    public R<Student> login(@RequestBody Student student, HttpServletRequest request){

        //根据学号查询学生信息
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getStuNo,student.getStuNo());
        Student stu = studentService.getOne(queryWrapper);
        if (stu == null){
            return R.error("该学号不存在，登录失败！");
        }

        //密码加密
        String password = student.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if(!stu.getPassword().equals(password)){
            return R.error("密码不正确，登录失败");
        }

        //登录成功，id存入session并返回
        request.getSession().setAttribute("studentId",stu.getId());
        log.info(stu.getId().toString());
        return R.success(stu);
    }

    /**
     * 学生退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("studentId");
        return R.success("退出成功");
    }

    /**
     * 学生更改密码
     * @param id
     * @param oldPass
     * @param newPass
     * @return
     */
    @PostMapping("/password")
    public R<String> changePass(String id,String oldPass,String newPass){
        //查询学生
        Student stu = studentService.getById(id);
        if(stu == null){
            return R.error("该学生不存在");
        }

        //学生存在  对旧密码进行加密
        oldPass = DigestUtils.md5DigestAsHex(oldPass.getBytes());
        if(!oldPass.equals(stu.getPassword())){
            return R.error("原密码输入有误");
        }

        //对新密码加密并存储
        newPass = DigestUtils.md5DigestAsHex(newPass.getBytes());
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set("password",newPass);
        studentService.update(updateWrapper);
        return R.success("修改密码成功");
    }

    /**
     * 学生上传头像
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/uploadavatar")
    public R<String> upload(HttpServletRequest request, MultipartFile file){
        //接受当前学生id
        //注意，当用户为登录时，即session中没有存储东西的时候，过滤器也没有拦截的话，会爆空指针异常
        String id = null;
        try {
            id = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("你没登录呢");
        }
        //根据id查询学号
        Student stu = studentService.getById(id);
        String stuNo = stu.getStuNo();


        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //学生头像存储路径  需要被覆盖
        String avatar = avatarPath + stuNo + suffix;
        log.info(avatar);



        try {
            //临时文件转存到指定位置
            file.transferTo(new File(avatar));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //将更新好的头像路径存储进数据库  为了安全其间，不暴露文件存储路径 将avatarPath去掉
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        avatar = stuNo + suffix;//将路径去除
        updateWrapper.set("avatar",avatar);
        studentService.update(updateWrapper);

        return R.success(avatar);
    }

    /**
     * 学生头像下载
     * @param name  图片名称  D:\\digitalTwin\\avatar\\185777.jpg 登录成功后，前端返回了
     * @param response
     */
    @GetMapping("/downloadavatar")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流  读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(avatarPath + name));

            //输出流   将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            //输入流每次读取1024字节的长度
            while ((len = fileInputStream.read(bytes) )!= -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭流
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 学生端开启内压实验
//     * @param stuNo
     * @return
     */
    @PostMapping("/stuStartNeiyaExp")
    public R<String> stuStartNeiyaExp(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        //判断该标志位是否为On
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String neiyaFlag = student.getNeiyaFlag();
        if (!"On".equals(neiyaFlag)){
            return R.error("学生端不能开始实验");
        }
        return R.success("学生可以开始实验");
    }

    /**
     * 学生端开启外压实验
//     * @param stuNo
     * @return
     */
    @PostMapping("/stuStartWaiyaExp")
    public R<String> stuStartWaiyaExp(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        //判断该标志位是否为On
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String waiyaFlag = student.getWaiyaFlag();
        if (!"On".equals(waiyaFlag)){
            return R.error("学生端不能开始实验");
        }
        return R.success("学生可以开始实验");
    }

    /**
     * 学生端开启爆破实验
//     * @param stuNo
     * @return
     */
    @PostMapping("/stuStartBaopoExp")
    public R<String> stuStartBaopoExp(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        //判断该标志位是否为On
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String baopoFlag = student.getBaopoFlag();
        if (!"On".equals(baopoFlag)){
            return R.error("学生端不能开始实验");
        }
        return R.success("学生可以开始实验");
    }

    /**
     * 学生端获取外压实验参数
     * @param stuNo
     * @return
     */
    @PostMapping("/getWaiyaParams")
    public R<Waiyacontrol> getWaiyaParams(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String waiyaFlag = student.getWaiyaFlag();
        if (!"On".equals(waiyaFlag)){
            return R.error("学生端不能开始实验");
        }

        QueryWrapper<Waiyacontrol> waiyacontrolQueryWrapper = new QueryWrapper<>();
        waiyacontrolQueryWrapper.eq("id","1");
        Waiyacontrol waiyacontrol = waiyacontrolService.getOne(waiyacontrolQueryWrapper);
        return R.success(waiyacontrol);
    }

    /**
     * #3 20240818
     * 学生端获取外压实验参数 获取一个随机值
     * @param stuNo
     * @return
     */
    @PostMapping("/getWaiyaRandomParams")
    public R<Waiyacontrol> getWaiyaRandomParams(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
//        String waiyaFlag = student.getWaiyaFlag();
//        if (!"On".equals(waiyaFlag)){
//            return R.error("学生端不能开始实验");
//        }

        QueryWrapper<Waiyacontrol> waiyacontrolQueryWrapper = new QueryWrapper<>();
        List<Waiyacontrol> waiyacontrol = waiyacontrolService.list(waiyacontrolQueryWrapper);
        Random rand = new Random();
        return R.success(waiyacontrol.get(rand.nextInt(waiyacontrol.size())));
    }

    /**
     * 学生端获取内压实验参数
     * @param stuNo
     * @return
     */
    @PostMapping("/getNeiyaParams")
    public R<Neiyacontrol> getNeiyaParams(String stuNo){
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String neiyaFlag = student.getNeiyaFlag();
        if (!"On".equals(neiyaFlag)){
            return R.error("学生端不能开始实验");
        }

        QueryWrapper<Neiyacontrol> neiyacontrolQueryWrapper = new QueryWrapper<>();
        neiyacontrolQueryWrapper.eq("id","1");
        Neiyacontrol neiyacontrol = neiyacontrolService.getOne(neiyacontrolQueryWrapper);
        return R.success(neiyacontrol);
    }

    /**
     * 学生端获取爆破实验参数
//     * @param stuNo
     * @return
     */
    @PostMapping("/getBaopoParams")
    public R<Baopocontrol> getBaopoParams(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String baopoFlag = student.getBaopoFlag();
        if (!"On".equals(baopoFlag)){
            return R.error("学生端不能开始实验");
        }

        QueryWrapper<Baopocontrol> baopocontrolQueryWrapper = new QueryWrapper<>();
        baopocontrolQueryWrapper.eq("id",1);
        Baopocontrol baopocontrol = baopocontrolService.getOne(baopocontrolQueryWrapper);
        return R.success(baopocontrol);
    }

    /**
     * #3 20240818
     * 学生端获取爆破实验参数 获取一个随机值
     //     * @param stuNo
     * @return
     */
    @PostMapping("/getBaopoRandomParams")
    public R<Baopocontrol> getBaopoRandomParams(@RequestBody Map<String, String> requestBody){
        String stuNo = requestBody.get("stuNo");
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
//        String baopoFlag = student.getBaopoFlag();
//        if (!"On".equals(baopoFlag)){
//            return R.error("学生端不能开始实验");
//        }

        QueryWrapper<Baopocontrol> baopocontrolQueryWrapper = new QueryWrapper<>();
        List<Baopocontrol> baopocontrol = baopocontrolService.list(baopocontrolQueryWrapper);
        Random rand = new Random();
        return R.success(baopocontrol.get(rand.nextInt(baopocontrol.size())));
    }


    /**
     * #1 #2
     * 获取内压状态
     * @return
     */
    @GetMapping("/getNeiyaStatus")
    public R<Boolean> getNeiyaStatus(@RequestParam String stuNo){
        //判断该标志位是否为On
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String neiyaFlag = student.getNeiyaFlag();
        if ("On".equals(neiyaFlag)){
            return R.success(true);
        }
        return R.success(false);
    }

    /**
     * #1 #2
     * 获取爆破状态
     * @return
     */
    @GetMapping("/getBaopoStatus")
    public R<Boolean> getBaopoStatus(@RequestParam String stuNo){
        //判断该标志位是否为On
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String baopoFlag = student.getBaopoFlag();
        if ("On".equals(baopoFlag)){
            return R.success(true);
        }
        return R.success(false);
    }

    /**
     * #1 #2
     * 获取外压状态
     * @return
     */
    @GetMapping("/getWaiyaStatus")
    public R<Boolean> getWaiyaStatus(@RequestParam String stuNo){
        //判断该标志位是否为On
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        Student student = studentService.getOne(queryWrapper);

        //这里返回的标志位可以自己设定
        String waiyaFlag = student.getWaiyaFlag();
        if ("On".equals(waiyaFlag)){
            return R.success(true);
        }
        return R.success(false);
    }
}
